using AutoMapper;
using BaseData.Domain;
using BaseData.ReadApi.Appcontext.Command.EweHistoryRecord_Files;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace BaseData.ReadApi.Appcontext.CommandHandler.EweHistoryRecord_Files
{
    /// <summary>
    /// 获取种母历史记录详情命令处理器
    /// </summary>
    public class GetEweHistoryRecordDetailCommandHandler : IRequestHandler<GetEweHistoryRecordDetailCommand, ApiResult<EweHistoryRecordDetailDto>>
    {
        private readonly IBaseRepository<EweHistoryRecord> _eweHistoryRecordRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetEweHistoryRecordDetailCommandHandler> _logger;

        public GetEweHistoryRecordDetailCommandHandler(
            IBaseRepository<EweHistoryRecord> eweHistoryRecordRepository,
            IMapper mapper,
            ILogger<GetEweHistoryRecordDetailCommandHandler> logger)
        {
            _eweHistoryRecordRepository = eweHistoryRecordRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取种母历史记录详情命令
        /// </summary>
        /// <param name="request">查询命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>详情查询结果</returns>
        public async Task<ApiResult<EweHistoryRecordDetailDto>> Handle(GetEweHistoryRecordDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证请求参数
                if (request == null)
                {
                    _logger.LogWarning("获取种母历史记录详情请求参数为空");
                    return new ApiResult<EweHistoryRecordDetailDto> { Code = ApiEnum.查询失败, Message = "请求参数不能为空", data = null };
                }

                // 验证数据
                if (!request.Validate(out string errorMessage))
                {
                    _logger.LogWarning($"获取种母历史记录详情数据验证失败: {errorMessage}");
                    return new ApiResult<EweHistoryRecordDetailDto> { Code = ApiEnum.查询失败, Message = errorMessage, data = null };
                }

                // 根据ID查询种母历史记录
                var eweHistoryRecord = await _eweHistoryRecordRepository.GetAll()
                    .Where(e => e.HistoryId == request.HistoryId && !e.IsDeleted)
                    .FirstOrDefaultAsync(cancellationToken);
                
                if (eweHistoryRecord == null)
                {
                    _logger.LogWarning($"未找到ID为 {request.HistoryId} 的种母历史记录");
                    return new ApiResult<EweHistoryRecordDetailDto> { Code = ApiEnum.查询失败, Message = "未找到指定的种母历史记录", data = null };
                }

                // 构建详情DTO
                var detailDto = new EweHistoryRecordDetailDto
                {
                    HistoryId = eweHistoryRecord.HistoryId,
                    EweId = eweHistoryRecord.EweId,
                    MatingDate = eweHistoryRecord.MatingDate,
                    RamId = eweHistoryRecord.RamId,
                    PregnancyCheckDate = eweHistoryRecord.PregnancyCheckDate,
                    PregnancyResult = eweHistoryRecord.PregnancyResult,
                    DeliveryDate = eweHistoryRecord.DeliveryDate,
                    HealthyLambCount = eweHistoryRecord.HealthyLambCount,
                    HealthyLambTotalWeight = eweHistoryRecord.HealthyLambTotalWeight,
                    WeakLambCount = eweHistoryRecord.WeakLambCount,
                    DeformedCount = eweHistoryRecord.DeformedCount,
                    StillbirthCount = eweHistoryRecord.StillbirthCount,
                    MummyCount = eweHistoryRecord.MummyCount,
                    AbnormalCount = eweHistoryRecord.AbnormalCount,
                    CurrentParity = eweHistoryRecord.CurrentParity,
                    Note = eweHistoryRecord.Note,
                    IsDeleted = eweHistoryRecord.IsDeleted,
                    Initialstate = eweHistoryRecord.Initialstate,

                };

                _logger.LogInformation($"成功获取种母历史记录详情，ID: {request.HistoryId}");
                
                return new ApiResult<EweHistoryRecordDetailDto>
                {
                    Code = ApiEnum.查询成功,
                    Message = "种母历史记录详情获取成功",
                    data = detailDto
                };
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning($"参数验证异常: {ex.Message}");
                return new ApiResult<EweHistoryRecordDetailDto> { Code = ApiEnum.查询失败, Message = ex.Message, data = null };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取种母历史记录详情时发生系统异常: {ex.Message}");
                return new ApiResult<EweHistoryRecordDetailDto> { Code = ApiEnum.查询失败, Message = "系统异常，请联系管理员", data = null };
            }
        }
    }
}